package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 角色权限工具类
 * 提供获取当前用户角色和ID的便捷方法
 */
public class RoleUtils {

    /**
     * 从当前请求中获取用户角色
     * @return 用户角色 (USER 或 HR)
     */
    public static String getCurrentUserRole() {
        try {
            HttpServletRequest request = getCurrentRequest();
            if (request == null) {
                return null;
            }

            String authorizationHeader = request.getHeader("Authorization");
            if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                return null;
            }

            String jwt = authorizationHeader.substring(7);
            Claims claims = JwtUtils.parseJWT(jwt);
            return (String) claims.get("role");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从当前请求中获取用户ID
     * @return 用户ID
     */
    public static Integer getCurrentUserId() {
        try {
            HttpServletRequest request = getCurrentRequest();
            if (request == null) {
                return null;
            }

            String authorizationHeader = request.getHeader("Authorization");
            if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
                return null;
            }

            String jwt = authorizationHeader.substring(7);
            Claims claims = JwtUtils.parseJWT(jwt);
            return (Integer) claims.get("id");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查当前用户是否为HR
     * @return true表示是HR，false表示不是
     */
    public static boolean isHR() {
        return "HR".equals(getCurrentUserRole());
    }

    /**
     * 检查当前用户是否为普通用户
     * @return true表示是普通用户，false表示不是
     */
    public static boolean isUser() {
        return "USER".equals(getCurrentUserRole());
    }

    /**
     * 获取当前HTTP请求对象
     * @return HttpServletRequest对象
     */
    private static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
}

